package com.haierp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.model.SellerItemDimensioncode;
import com.haierp.service.ISellerItemDimensioncodeService;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.JsonResult;
import com.haierp.util.PropertiesUtils;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.google.common.collect.Maps;
import com.haierp.mapper.ActivityDetailMapper;
import com.haierp.mapper.ActivityMapper;
import com.haierp.model.Item;
import com.haierp.model.activity.Activity;
import com.haierp.model.activity.ActivityDetail;
import com.haierp.service.IActivityService;
import com.haierp.service.IItemService;
import com.haierp.util.JsonPageResult;
import com.haierp.vo.ActivityQueryVO;

@Service
public class ActivityServiceImpl extends SuperServiceImpl<ActivityMapper, Activity>
		implements IActivityService {
	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private ActivityDetailMapper activityDetailMapper;
	@Autowired
	private IItemService itemService;
	@Autowired
	private ISellerItemDimensioncodeService sellerItemDimensioncodeService;


	public static final String getaccess_tokenurl = "https://api.weixin.qq.com/cgi-bin/token";
	public static final String getaccess_tokenparam = "grant_type=client_credential&appid="+PropertiesUtils.getProperties().getProperty("wx.sale.appId")+"&secret="+PropertiesUtils.getProperties().getProperty("wx.sale.appSecret");
	@Override
	public void addActivity(Activity activity) {
		activityMapper.insertSelective(activity);
		if (activity.getActivityDetails() != null && !activity.getActivityDetails().isEmpty()) {
			List<ActivityDetail> activityDetails = activity.getActivityDetails();
			activityDetails.forEach(activityDetail -> {
				activityDetail.setActivityId(activity.getId());
				activityDetail.setGmtCreate(new Date());
				activityDetail.setGmtModify(new Date());
				Item item = new Item();
				item.setItemCode(activityDetail.getItemCode());
				Item selItem = itemService.selectOne(item);
				if (selItem != null) {
					activityDetail.setCompanyId(selItem.getCompanyId());
					activityDetail.setItemId(selItem.getId());
					activityDetail.setItemCode(selItem.getItemCode());
				}
			});
			activityDetailMapper.insertBatch(activityDetails);
		}
		
	}

	@Override
	public void updateActivity(Activity activity) {
		activityMapper.updateSelectiveById(activity);
		List<ActivityDetail> activityList = activity.getActivityDetails();
		List<ActivityDetail> activityListNew = new ArrayList<>();
		List<ActivityDetail> activityDetailListtUpdate = new ArrayList<>();
		// 获取数据库里面的所有sku
		Activity activitySelect = queryActivity(activity.getId());
		List<ActivityDetail> activityDetailListDb = activitySelect.getActivityDetails();
		Set<Long> allDetails = new HashSet<Long>();
		Map<Long,ActivityDetail> detailMap = Maps.newHashMap();
		if (activityDetailListDb != null && !activityDetailListDb.isEmpty()) {
			activityDetailListDb.forEach(detail -> {
				allDetails.add(detail.getId());
				detailMap.put(detail.getId(), detail);
			});
		}
		activityList.forEach(detail -> {
			if (detail.getId() == null) {
				detail.setActivityId(activity.getId());
				detail.setGmtCreate(new Date());
				detail.setGmtModify(new Date());
				activityListNew.add(detail);
			} else {
				if (!allDetails.isEmpty()) {
					allDetails.remove(detail.getId());
				}
				detail.setGmtModify(new Date());
				activityDetailListtUpdate.add(detail);
			}
			Item item = new Item();
			item.setItemCode(detail.getItemCode());
			Item selItem = itemService.selectOne(item);
			if (selItem != null) {
				detail.setCompanyId(selItem.getCompanyId());
				detail.setItemId(selItem.getId());
				detail.setItemCode(selItem.getItemCode());
			}
		});
		if (!activityDetailListtUpdate.isEmpty()) {
			activityDetailMapper.updateBatchById(activityDetailListtUpdate);
		}
		if (!activityListNew.isEmpty()) {
			activityListNew.forEach(detail-> {
				detail.setCompanyId(activity.getCompanyId());
			});
			activityDetailMapper.insertBatch(activityListNew);
		}
		if (!allDetails.isEmpty()) {
			activityDetailMapper.deleteBatchIds(new ArrayList<Long>(allDetails));
		}
	}

	@Override
	public void deleteActivity(Activity activity) {
		// 删除主题
		activityMapper.deleteById(activity.getId());
		Map<String, Object> columnMap = new HashMap<>();
		// 删除主题明细
		columnMap.put("activity_id", activity.getId());
		activityDetailMapper.deleteByMap(columnMap);
	}

	@Override
	public Activity queryActivity(Long activityId) {
		if (activityId == null) {
			throw new RuntimeException("the activity id is null");
		}
		Activity activity = activityMapper.selectById(activityId);

		if (activity != null) {
			List<ActivityDetail> activityDetails = activityDetailMapper.selectActivityDetailByActivityId(activityId);
			if (activityDetails != null) {
				for (ActivityDetail a:activityDetails) {
					SellerItemDimensioncode sellerItemDimensioncode = new SellerItemDimensioncode();
					sellerItemDimensioncode.setItemId(a.getItemId());
					sellerItemDimensioncode.setSellerId(activityId+100000L);
					EntityWrapper<SellerItemDimensioncode> entityWrapper = new EntityWrapper<>();
					entityWrapper.setEntity(sellerItemDimensioncode);
					SellerItemDimensioncode sel = sellerItemDimensioncodeService.selectOne(entityWrapper);
					if(sel != null) {
						a.setActivityItemDimensioncode(sel.getDimensioncodePic());
					}
				}
				activity.setActivityDetails(activityDetails);
			}
		}
		return activity;
	}

	@Override
	public JsonPageResult<List<Activity>> queryOuterOrderList(ActivityQueryVO activityQueryVO) {
		JsonPageResult<List<Activity>> activityResult = new JsonPageResult<>();
		// 1、查询总的记录数量
		Integer totalCount = activityMapper.queryActivityCount(activityQueryVO);
		// 2、查询分页记录
		if (totalCount != null && totalCount != 0L) {
			activityResult.buildPage(totalCount, activityQueryVO);
			List<Activity> activitys = activityMapper.queryActivitys(activityQueryVO);
			activityResult.setData(activitys);
		} else {
			List<Activity> activitys = new ArrayList<>();
			activityResult.setData(activitys);
		}
		return activityResult;
	}

	@Override
	public JsonResult<String> createActivityItemDimensioncode(Long itemId, Long activityId) {
		JsonResult<String> result = new JsonResult<>();
		SellerItemDimensioncode tj = new SellerItemDimensioncode();
		tj.setSellerId(activityId+100000L);
		tj.setItemId(itemId);
		SellerItemDimensioncode tjSellerItemDimensioncode = sellerItemDimensioncodeService.selectOne(tj);
		if(tjSellerItemDimensioncode !=null) {
			return result.buildData(tjSellerItemDimensioncode.getDimensioncodePic()).buildIsSuccess(true);
		}
		String reponse = DimensionCodeUtil.sendGet(getaccess_tokenurl, getaccess_tokenparam);
		JSONObject myJson = JSONObject.fromObject(reponse);
		String token = (String) myJson.get("access_token");
		String sceneStr = itemId.toString()+"_"+(activityId+100000L);
		String picUrl = itemService.insertIntoItemDimension(sceneStr, "pages/itemDetail/itemDetail", token);
		SellerItemDimensioncode sellerItemDimensioncode = new SellerItemDimensioncode();
		sellerItemDimensioncode.setItemId(itemId);
		sellerItemDimensioncode.setSellerId(activityId+100000L);
		sellerItemDimensioncode.setDimensioncodePic(picUrl);
		sellerItemDimensioncode.setGmtModify(new Date());
		sellerItemDimensioncode.setGmtCreate(new Date());
		sellerItemDimensioncodeService.insert(sellerItemDimensioncode);
		return result.buildIsSuccess(true).buildData(picUrl);
	}
}
